<template>
  <div class="login-container flex" ref="loading">
    <img src="../../../public/img/login-left.png" class="login-left" />
    <div class="login-right flex flex-col">
      <div class="fz-20 text-center text-bold">欢迎登录XX管理平台</div>
      <div class="text-center mb-20">WELCOME</div>
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item class="login-input flex" prop="name">
          <el-icon class="flex1">
            <User />
          </el-icon>
          <el-input class="login-input-right" v-model="form.name" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item class="login-input flex" prop="password">
          <el-icon class="flex1">
            <Lock />
          </el-icon>
          <el-input type="password" class="login-input-right" v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item>
          <el-checkbox class="login-remember mb-10" v-model="remember" label="记住密码" />
        </el-form-item>
        <el-form-item>
          <el-button class="login-btn w-p-100" type="primary" @click="onSubmit()">立即登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { useRouter } from "vue-router"; // Vue3组合式API
import { ElMessage } from "element-plus";
const router = useRouter();
import { ref, reactive } from "vue";
import axios from "axios";
import { ElLoading } from 'element-plus'
const ruleForm = ref(null);
const loading = ref()
const form = reactive({
  name: "",
  password: "",
});

const remember = ref(false);

const rules = {
  name: [{ required: true, message: "请输入账号", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
};

// 修改为异步函数，支持表单验证的await调用
const onSubmit = async () => {
  // 1. 表单验证（使用Element Plus表单验证功能）
  let valid = false;
  try {
    // 调用表单验证方法，验证通过返回true，失败抛出错误
    valid = await ruleForm.value.validate();
  } catch (error) {
    // 验证失败，直接拦截登录
    ElMessage.error("请完善登录信息");
    return;
  }

  // 2. 验证通过后执行登录逻辑
  const loadingInstance = ElLoading.service({
    target: loading.value,
    text: '登录中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  if (valid) {
    await axios
      .post("http://127.0.0.1:8081/vaccine/user/login", {
        username: form.name,
        password: form.password,
      })
      .then((req) => {
        console.log(req.data);
        if (req.data.success === false) {
          ElMessage({
            message: req.data.message,
            type: "error",
          });
        } else {
          const mockLoginSuccess = true;
          if (mockLoginSuccess) {
            // 存储token并跳转首页
            sessionStorage.setItem('token', req.data.token);
            router.push('/');
            ElMessage({
              message: '登录成功',
              type: 'success',
            });

          } else {

            ElMessage.error('登录失败');

          }
        }
      })
      .catch((error) => {
        console.error('登录请求失败:', error);
        ElMessage.error('登录失败，请检查网络连接');
      })
      .finally(() => {
        loadingInstance.close();
      });
  }
};
</script>

<style scoped>
@import "/src/assets/expand.css";

.login-container {
  width: 100vw;
  height: 100vh;
  background: url("../../../public/img/login.png") no-repeat;
  background-size: cover;
}

.login-left {
  width: 58%;
  height: 100%;
}

.login-right {
  width: 25%;
  height: 56%;
  background-color: #fff;
  margin: auto;
  border-radius: 10px;
  box-shadow: #b3d2fb 1px 1px 15px 1px;
  padding: 40px 30px;
}

.login-input {
  height: 50px;
  border: 1px solid #b3d2fb;
  border-radius: 5px;
  background: rgba(231, 241, 253, 0.4);
}

.login-input-right {
  width: 80%;
  height: 60%;
  border-left: 1px solid #ccc;
}

.login-remember {
  font-size: 12px;
}

.login-btn {
  height: 40px;
}
</style>
<style>
.login-input-right .el-input__wrapper {
  border: none !important;
  box-shadow: none !important;
  background: transparent;
}

.login-remember .el-checkbox__label {
  font-size: 12px;
  color: #aaa;
}
</style>
